<?php 
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 商品表
 */
class Goods_mdl extends CI_Model{
	
	const TABLE = 'goods';
	
	public $sortAll = array(); 
	
	/**
	 * 查询列表
	 */
	public function select(){
		$query = $this->db->get(self::TABLE);
		return $query->result_array();
	}
	
	/**
	 * 查询单个数据
	 */
	public function get_one(){
		return $this->db->get(self::TABLE)->row_array();
	}
	
	/**
	 * 商品添加
	 */
	public function create($data){
		return $this->db->insert(self::TABLE,$data);
	}
	
	/**
	 * 商品修改
	 */
	public function update($data){
		return $this->db->update(self::TABLE,$data);
	}
	
	/**
	 * 数据统计
	 */
	public function get_count(){
		$res = $this->db->count_all_results(self::TABLE);
		//echo $this->db->last_query();
		return $res;
	}
	
	/**
	 * 商品数据整合
	 */
	public function restr($list){
		foreach($list as $k => $v){
			//分类整合
			if(isset($v['sort_id'])){
				if(empty($this->sortAll)){
					$this->db->select('id,name,pid');
					$this->load->model('sort_mdl');
					$this->sortAll = $this->sort_mdl->select();
				}
				foreach($this->sortAll as $ket => $value){
					if($value['id'] == $v['sort_id']){
						$list[$k]['sort_name'] = $value['name'];
						break;
					}
				}
			}

			//查询所属店铺
			if(isset($v['store_id'])){
				$this->load->model('store_mdl');
				$this->db->select('id,s_name');
				$this->db->where('id',$v['store_id']);
				$res = $this->store_mdl->get_one();
				$list[$k]['store'] = $res;
			}
		}
		
		return $list;
	}

	/**
	 * 删除商品相关的属性
	 * xg 相关
	 */
	public function delete($gid = 0){
		$gid = intval($gid);

		$this->db->start_cache();
		$this->db->where('goods_id',$gid);
		$this->db->stop_cache();

		//商品属性（二）
		$this->load->model('goodsval_mdl');
		$this->goodsval_mdl->delete();

		//分类属性
		$this->load->model('value_mdl');
		$this->goodsval_mdl->delete();

		//删除图片表和图片
		$this->load->model('image_mdl');
		$this->image_mdl->delete();

		$this->db->flush_cache();

		//删除文件夹
		$path = './upload/goods/'.$gid.'/';
		$this->deldir($path); 

		$this->db->where('id',$gid);
		$res = $this->db->delete(self::TABLE);
		return $res;
	}

	public function deldir($dir) {
	  //先删除目录下的文件：
	  $dh=opendir($dir);
	  while ($file=readdir($dh)) {
	    if($file!="." && $file!="..") {
	      $fullpath=$dir."/".$file;
	      if(!is_dir($fullpath)) {
	          unlink($fullpath);
	      } else {
	          deldir($fullpath);
	      }
	    }
	  }
	  
	  closedir($dh);
	  //删除当前文件夹：
	  if(rmdir($dir)) {
	    return true;
	  } else {
	    return false;
	  }
	}
}
